/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.servlet;

import com.kamus.Constants;
import com.kamus.manager.FileDbMgr;
import com.kamus.model.FileDb;
import com.util.CommonUtil;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;
import java.util.Vector;
import javax.servlet.ServletException;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import sax.MyElement;
import sax.MySAXParserBean;

/**
 *
 * @author omega
 */
public class UpdateServlet extends HttpServlet {

    /** 
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        PrintWriter out = response.getWriter();
        Date dateGIClient = null, dateIGClient = null;
        ServletInputStream sis = request.getInputStream();
        MySAXParserBean p = new MySAXParserBean();
        try {
            Vector v = p.parse(sis);
            MyElement element;
            for (int i = 0; i < v.size(); i++) {
                element = (MyElement) v.elementAt(i);
                String tag = element.getQname();
                if (tag.equals("date_gi")) {
                    dateGIClient = new Date(Long.parseLong(element.getValue()));
                } else if (tag.equals("date_ig")) {
                    dateIGClient = new Date(Long.parseLong(element.getValue()));
                }
            }
        } catch (Exception e) {
            response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
            return;
        }

        FileDb fileGI = null, fileIG = null;
        try {
            FileDbMgr fdm = FileDbMgr.getInstance();
            fileGI = fdm.getUsed(FileDbMgr.TYPE_GI);
            fileIG = fdm.getUsed(FileDbMgr.TYPE_IG);
            int code = 0;
            // check database file GI
            if (fileGI.getTanggal().after(dateGIClient)) {
//                String content = CommonUtil.inputStreamToString(CommonUtil.readGzip(Constants.PATH + fileGI.getNama()+".dat"));
                String content = CommonUtil.inputStreamToString(CommonUtil.readFile(Constants.PATH + fileGI.getNama()+".dat"));
                fileGI.setContent(content);
                code++;
            } else {
                fileGI.setContent("");
            }
            //check database file IG
            if (fileIG.getTanggal().after(dateIGClient)) {
//                String content = CommonUtil.inputStreamToString(CommonUtil.readGzip(Constants.PATH + fileIG.getNama()+".dat"));
                String content = CommonUtil.inputStreamToString(CommonUtil.readFile(Constants.PATH + fileIG.getNama()+".dat"));
                fileIG.setContent(content);
                code++;
            } else {
                fileIG.setContent("");
            }

            String msg = "";
            if (code == 0) {
                msg = "None Databases were updated";
            } else if (code == 1) {
                msg = "One of Databases was updated";
            } else if (code == 2) {
                msg = "Both of databases were updated";
            }
            out.print(generateResponse(code, msg, fileGI, fileIG));
        } catch (Exception e) {
            e.printStackTrace();
            fileGI=new FileDb();
            fileIG=new FileDb();
            fileGI.setTanggal(dateGIClient);
            fileGI.setContent("");
            fileIG.setTanggal(dateIGClient);
            fileIG.setContent("");
            out.print(generateResponse(-1, e.getMessage(), fileGI, fileIG));
        }
    }

    private String generateResponse(int code, String msg, FileDb fileGI, FileDb fileIG) {
        StringBuffer dataResponse = new StringBuffer();
        dataResponse.append("<xml>").append("<code>").append(code).append("</code>").append("<msg>").append(msg).append("</msg>").append("<db name=\"gi\">").append("<content>").append(fileGI.getContent()).append("</content>").append("<date>").append(fileGI.getTanggal().getTime()).append("</date>").append("</db>").append("<db name=\"ig\">").append("<content>").append(fileIG.getContent()).append("</content>").append("<date>").append(fileIG.getTanggal().getTime()).append("</date>").append("</db>").append("</xml>");
        return dataResponse.toString();
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /** 
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
